'use strict';
const Service = require('egg').Service;

class OrdersService extends Service {
  async index (filters, pages) {
    const orders = await this.app.api.orders.getListOrders(filters, pages);
    let productSnapshots;
    if (orders) {
      let snapshotIds = [];
      for (const order of orders) {
        for (let product of order.orderProducts) {
          if (+product.snapshot > 0) {
            snapshotIds.push(product.snapshot);
          }
        }
      }
      // id去除重复
      snapshotIds = [...new Set(snapshotIds)];
      productSnapshots = await this.app.api.productSnapshots.get(snapshotIds);
      if (snapshotIds.length === 1) {
        productSnapshots = [productSnapshots];
      }
    }

    const imgHost = this.app.config.qiniu.bucket.subImg.host;
    return {
      imgHost,
      orders,
      productSnapshots
    };
  }
  async create (userId, shopId, comment, productList, systemComment) {
    // 查看产品是否啥店铺产品 并且是可购买状态
    let productIds = [];
    for (let product of productList) {
      productIds.push(product.productId);
    }

    productIds = [...new Set(productIds)];

    let products = await this.app.api.products.getProductDetail(productIds);

    if (products) {
      if (productIds.length === 1) {
        products = [products];
      }

      if (productIds.length !== products.length) {
        this.ctx.throw(422, '产品不全');
        return null;
      }
      for (const product of products) {
        if (+product.user.id !== +shopId) {
          this.ctx.logger.warn(`下单产品和店铺id不符 product.user.id: ${product.user.id}; shopId: ${shopId}`);
          this.ctx.throw(422, '产品不属于该店铺');
          return null;
        }
        if (+product.status !== 2) {
          this.ctx.throw(422, '产品未上架');
          return null;
        }
      }
    } else {
      this.ctx.throw(422, '产品不存在');
      return null;
    }

    const order = await this.app.api.orders.createOrder(userId, shopId, comment, productList, systemComment);
    return {
      order
    };
  }
  async show (id) {
    const order = await this.app.api.orders.getOrderDetail(id);
    let productSnapshots;
    if (order) {
      let snapshotIds = [];
      for (let product of order.orderProducts) {
        if (+product.snapshot > 0) {
          snapshotIds.push(product.snapshot);
        }
      }
      // id去除重复
      snapshotIds = [...new Set(snapshotIds)];
      productSnapshots = await this.app.api.productSnapshots.get(snapshotIds);
      if (snapshotIds.length === 1) {
        productSnapshots = [productSnapshots];
      }
    }

    return {
      order,
      productSnapshots
    };
  }
  async pay (id, payType, payComment) {
    const payData = await this.app.api.orders.changeOrderPay(id, payType, payComment);
    return {
      payResult: payData
    };
  }
}

module.exports = OrdersService;
